package light.head.controller.oa;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.ApplyInfoDAO;
import light.head.dao.oa.AuditStatusDAO;
import light.head.dao.oa.ProcessConfigDAO;
import light.head.dao.sys.MessageDAO;
import light.head.dao.sys.MessageTemplateDAO;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.ApplyInfo;
import light.head.model.ApplyItem;
import light.head.model.AuditStatus;
import light.head.model.ProcessConfig;
import light.head.model.UserInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/***
 * 物品申请信息
 * @author yy
 *
 */
@Controller
@RequestMapping(Url.C_APPLY)
public class ApplyController extends SupporterController{

	private ApplyInfoDAO applyDAO;
	private OrganDAO organDAO;
	private ProcessConfigDAO pcDAO;
	private AuditStatusDAO auDAO;
	private UserInfoDAO userDAO;
	private MessageDAO msgDAO;
	private MessageTemplateDAO mtDAO;

	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception{
		return new ModelAndView(Url.APPLY_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.DELETED,Parm.TITLE, Parm.TIME1, Parm.TIME2, Parm.STATUS);
		if (applyDAO.findByMap_2(cu_code(request), map, pb) == RESULT.SUCCESS) {
			// 讲对应的审核状态放到对应的
			ApplyInfo applyInfo = null;
			for (Object o : pb.getResultList()) {
				applyInfo = (ApplyInfo) o;
				applyInfo.setAuditStatusList(auDAO.findByBusinessMc(Sys.B_ONE, applyInfo.getCode()));
			}
		}
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.APPLY_LIST);
	}
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(Integer code,HttpServletRequest request, HttpServletResponse response) throws Exception{
		if(code != null){
			ApplyInfo apply = applyDAO.get(code);
			List<ApplyItem> list = applyDAO.findApplyItem(code);
			apply.setAdList(list);
			request.setAttribute(Parm.APPLY, apply);
		}
		return new ModelAndView(Url.APPLY_EDIT);
	}

	//保存申请单
	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save(ApplyInfo apply, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (null == apply || null == apply.getAdList() || apply.getAdList().size() == 0 || apply.getSort() == null) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		if (apply.getSort() != null && apply.getSort() == 2) {
			List<ProcessConfig> pcList = pcDAO.findByOcBusiness(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_ONE);
			if (pcList == null || pcList.size() == 0 ) {
				print(response, Msg.EXISTS);
				return;	
			}
		}
		// 检查是否有可以保存的明细在保存,至少有一条明细可以保存
		boolean ok = true;
		for (ApplyItem Item : apply.getAdList()) {
			if (null != Item && null != Item.getGn() && null != Item.getCount() && Item.getCount().intValue() > 0 ) {
				ok = false;
			}
		}
		if (ok) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Integer code = null;
		if (apply.getCode() != null) {
			ApplyInfo old = applyDAO.get(apply.getCode());
			old.setAu(cu_code(request));
			old.setTitle(apply.getTitle().length() > 100 ? apply.getTitle().substring(0, 99) : apply.getTitle());
			result = applyDAO.upd(old);
			code = old.getCode();
		} else {
			apply.setAu(cu_code(request));
			apply.setOc(cu_organCode(request));
			if (apply.getTitle().length() > 100)
			apply.setTitle(apply.getTitle().substring(0, 99));
			apply.setDeleted(false);
			apply.setAt(new Date());
			apply.setStatus(Sys.B_TWO);
			
			result = applyDAO.add(apply);
			code = apply.getCode();
		}
		if (RESULT.SUCCESS == result) {
			List<ApplyItem> list = apply.getAdList();
			List<ApplyItem> oldList = applyDAO.findApplyItem(apply.getCode());
			
			for (ApplyItem pii : list) {
				if (null == pii.getCode()) {
					if (null != pii.getGn() && null != pii.getCount() && pii.getCount().intValue() > 0 ) {
						pii.setAcode(code);
						result = applyDAO.add(pii);
					}
				} else {
					if (null == pii.getCount() || pii.getCount().intValue() == 0 || null == pii.getGn()) {
						result = applyDAO.del(pii);
						continue;
					}
					
					for (ApplyItem old : oldList) {
						if (pii.getCode().intValue() == old.getCode().intValue() && (old.getCount().intValue() != pii.getCount().intValue())) {
							old.setCount(pii.getCount());
							old.setGn(pii.getGn());
							result = applyDAO.upd(old);
						}
					}
				}
			}
			int len = list.size();
			for (ApplyItem old : oldList) {
				int i = 0;
				for (; i < len; i ++) {
					if (null != old.getCode() && old.getCode().intValue() == list.get(i).getCode().intValue())
						break;
				}
				if (i == len){
					result = applyDAO.del(old);
				}
			}
			if (apply.getSort() != null && apply.getSort() == 2) {
				List<ProcessConfig> pcList = pcDAO.findByOcBusiness(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_ONE);
				if (pcList != null && pcList.size() > 0 ) {
					int i = 1;
					for (ProcessConfig pc : pcList) {
						AuditStatus au = new AuditStatus();
						au.setBusiness(Sys.B_ONE);
						au.setCt(new Date());
						au.setCu(cu_code(request));
						au.setOc(cu_organCode(request));
						au.setMc(apply.getCode());
						au.setRc(pc.getRc());
						au.setPcc(pc.getCode());
						au.setPc(pc.getPc());
						// 默认第一个审核节点的上一节点审核状态为1通过
						if (null != pc.getPc() && pc.getPc().intValue() == 1){
							au.setBeforeStatus(Sys.B_ONE);
						}
						if (null != pc.getPc() && pc.getPc().intValue() == 1 && null != cu_roleCode(request) && pc.getRc() == cu_roleCode(request)){
							au.setStatus(Sys.B_ONE);
							au.setAt(new Date());
							au.setAu(cu_code(request));
							i++;
						}
						if(null != pc.getPc() && pc.getPc().intValue() == 2 && i == 2){
							au.setBeforeStatus(Sys.B_ONE);
						}
						result = auDAO.add(au);
					}
				}
				// 消息通知审核人
				Integer rc = auDAO.findByBusinessOcMc(Sys.B_ONE, cu_organCode(request), apply.getCode());	// 获取该机构具有审核申请单的角色编号
				if (null != rc) {
					List<UserInfo> userList = userDAO.findByRoleRc(cu_organCode(request), rc);	// 获取有审核角色的所有用户
					List<Integer> rucs = new ArrayList<Integer>();
					for (UserInfo u : userList) {
						rucs.add(u.getCode());
					}
					String content = mtDAO.applyTofirst(apply, cu_realName(request));
					msgDAO.sendToUsers("【" + cu_realName(request) + "】提交申请待审核通知", content, cu_code(request), cu_organCode(request), rucs);
				}
			}
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
			return;
		}
	}
	

	@RequestMapping(value = Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		ApplyInfo apply = applyDAO.get(Integer.parseInt(code));
		if (apply == null) {
			print(response, Msg.NOT_FIND);
		} else {
			apply.setDeleted(true);
			if (applyDAO.upd(apply) == RESULT.SUCCESS) {
				print(response, Msg.SUCCESS);
			} else {
				print(response, Msg.ERROR);
			}
		}
	}
	
	
	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		ApplyInfo apply = applyDAO.get(Integer.parseInt(code));
		if (apply == null) {
			print(response, Msg.NOT_FIND);
		} else {
			apply.setDeleted(false);
			if (applyDAO.upd(apply) == RESULT.SUCCESS) {
				print(response, Msg.SUCCESS);
			} else 
				print(response, Msg.ERROR);
		}
	}
	
	// 单个申请单详情
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			ApplyInfo a = applyDAO.get(code);
			if (null != a) {
				a.setAuditStatusList(auDAO.findByBusinessMc(Sys.B_ONE, a.getCode()));
				List<ApplyItem> list = applyDAO.findApplyItem(code);
				a.setAdList(list);
				request.setAttribute(Parm.APPLY, a);
			}
		}
		return new ModelAndView(Url.APPLY_DETAIL);
	}
		
	@Autowired
	public void setApplyDAO(ApplyInfoDAO applyDAO) {
		this.applyDAO = applyDAO;
	}
	
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setPcDAO(ProcessConfigDAO pcDAO) {
		this.pcDAO = pcDAO;
	}
	@Autowired
	public void setAuDAO(AuditStatusDAO auDAO) {
		this.auDAO = auDAO;
	}
	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}
	@Autowired
	public void setMsgDAO(MessageDAO msgDAO) {
		this.msgDAO = msgDAO;
	}
	@Autowired
	public void setMtDAO(MessageTemplateDAO mtDAO) {
		this.mtDAO = mtDAO;
	}
	

}
